package com.rchat.pocmini.activity.chat;

import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.airtalkee.sdk.entity.AirSession;
import com.aso.common.utils.NetworkUtils;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.common.mvp.BaseMvpActivity;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTouch;

/**
 * Created by ljd on 2017/8/31.
 *
 */

public class ChatMvpActivity extends BaseMvpActivity<ChatPresenterImpl, ChatModelImpl>
        implements ChatContract.View{

    @BindView(R.id.tv_rtp_media_state)
    TextView tvRtpMediaState;//空闲状态

    @BindView(R.id.tv_rtp_speak)
    TextView tvRtpSpeak;//正再讲话状态

    @BindView(R.id.talk_time_chronometer)
    Chronometer timeChronometer;

    @BindView(R.id.dialog_voice)
    ImageView voiceLevel;

    @BindView(R.id.tv_group_name)
    TextView tvGroupName;

    @BindView(R.id.iv_back)
    View ivBack;

    //按住对讲键录制时的UI
    @BindView(R.id.ll_voice_level)
    LinearLayout llVoiceLevel;

    @BindView(R.id.iv_add_friend_to_group)
    View ivAddFriendToGroup;


    //频道id、name
    private String groupId;
    private String groupName;

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public int getLayoutId() {
        return R.layout.chat_activity_layout;
    }

    @Override
    public void initView() {
        groupId = getIntent().getStringExtra(GroupsPresenterImpl.KEY_GROUPID);
        groupName = getIntent().getStringExtra("groupName");
        tvGroupName.setText(groupName);
        tvRtpMediaState.setText(R.string.idle);

        mPresenter.sessionCall(groupId);
        talkingTip = getString(R.string.talking);
    }

    @Override
    public void doAfterInitView() {

    }


    @OnTouch({R.id.btn_talk})
    public boolean onTouch(View view, MotionEvent event){
        if (view.getId() == R.id.btn_talk) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                ALog.d("ACTION_UP...");
                //释放会话
                mPresenter.talkRelease();
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                ALog.d("ACTION_DOWN...");
                //开始讲话
                if (!NetworkUtils.isConnected()){
                    showNetError();
                    return true;
                }
                mPresenter.talkRequest();
            }
        }
        return true;
    }

    @OnClick({R.id.rl_group_members,
            R.id.rl_message_recorder,
            R.id.rl_location,
            R.id.iv_back,
            R.id.iv_add_friend_to_group})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_group_members:
                mPresenter.gotoGroupMemberActivity(groupName,groupId);
                break;
            case R.id.rl_message_recorder:
                mPresenter.gotoChatMessageActivity(groupName,groupId);
                break;
            case R.id.rl_location:
                mPresenter.gotoLocationActivity(groupName,groupId);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_add_friend_to_group:
                mPresenter.gotoInviteFriendToGroupActivity(groupId);
                break;
        }
    }

    @Override
    public void showVoiceLevel(int key) {
        if (llVoiceLevel != null && llVoiceLevel.getVisibility() == View.VISIBLE) {
            int level = 0;
            if (key < 40) {
                level = 1;
            } else if (key >= 40 && key < 45) {
                level = 2;
            } else if (key >= 45 && key < 50) {
                level = 3;
            } else if (key >= 50 && key < 55) {
                level = 4;
            } else if (key >= 55 && key < 60) {
                level = 5;
            } else if (key >= 60 && key < 65) {
                level = 6;
            } else if (key >= 65) {
                level = 7;
            }
            //通过level来找到图片的id
            int resId = getResources().getIdentifier("voice_level_" + level,
                    "drawable", getPackageName());

            voiceLevel.setImageResource(resId);
        }
    }

    @Override
    public void setSessionDisplay(AirSession airSession) {
        switch (airSession.getMediaButtonState()) {
            case AirSession.MEDIA_BUTTON_STATE_IDLE:
            case AirSession.MEDIA_BUTTON_STATE_TALKING:
                switch (airSession.getMediaState()) {
                    case AirSession.MEDIA_STATE_IDLE:
                        tvRtpMediaState.setText(R.string.idle);
                        llVoiceLevel.setVisibility(View.GONE);
                        tvRtpSpeak.setVisibility(View.GONE);
                        stopTime(timeChronometer);
                        tvRtpMediaState.setVisibility(View.VISIBLE);
                        break;
                    case AirSession.MEDIA_STATE_LISTEN:
                        if(!airSession.getSessionCode().equals(groupId)){
                            return;
                        }
                        tvRtpMediaState.setText(airSession.getSpeaker().getDisplayName() + talkingTip);
                        llVoiceLevel.setVisibility(View.GONE);
                        tvRtpSpeak.setVisibility(View.GONE);
                        timeChronometer.setVisibility(View.GONE);
                        tvRtpMediaState.setVisibility(View.VISIBLE);
                        break;
                    case AirSession.MEDIA_STATE_TALK:
                        tvRtpMediaState.setVisibility(View.GONE);
                        tvRtpSpeak.setVisibility(View.VISIBLE);
                        llVoiceLevel.setVisibility(View.VISIBLE);
                        startTime(timeChronometer, 0);
                        break;
                    default:
                        tvRtpMediaState.setText(R.string.idle);
                        llVoiceLevel.setVisibility(View.GONE);
                        tvRtpSpeak.setVisibility(View.GONE);
                        timeChronometer.setVisibility(View.GONE);
                        tvRtpMediaState.setVisibility(View.VISIBLE);
                        break;
                }
                break;
            case AirSession.MEDIA_BUTTON_STATE_CONNECTING:
            case AirSession.MEDIA_BUTTON_STATE_REQUESTING:
            case AirSession.MEDIA_BUTTON_STATE_QUEUE:
                tvRtpMediaState.setText(R.string.request_talk);
                tvRtpSpeak.setVisibility(View.GONE);
                timeChronometer.setVisibility(View.GONE);
                tvRtpMediaState.setVisibility(View.VISIBLE);
                llVoiceLevel.setVisibility(View.GONE);
                break;

            default:
                tvRtpMediaState.setText(R.string.idle);
                llVoiceLevel.setVisibility(View.GONE);
                tvRtpSpeak.setVisibility(View.GONE);
                timeChronometer.setVisibility(View.GONE);
                tvRtpMediaState.setVisibility(View.VISIBLE);
                break;
        }
    }

    private String talkingTip = "";
    private String timeLength = "01:00";//说话时间长度
    public static final int START_TIME = 1;
    public static final int STOP_TIME = 2;
    public Handler handler = new Handler() {
        public void handleMessage(Message paramAnonymousMessage) {
            super.handleMessage(paramAnonymousMessage);
            switch (paramAnonymousMessage.what) {
                case START_TIME:
                    break;
                case STOP_TIME:
                    if (paramAnonymousMessage.obj != null) {
                        stopTime((Chronometer) paramAnonymousMessage.obj);
                    }
                    break;
                default:

                    break;
            }
        }
    };

    /**
     * @param chronometer
     * @param startTimeMillis 起始显示时间
     */
    private void startTime(final Chronometer chronometer, long startTimeMillis) {
        if (chronometer != null) {
            chronometer.setVisibility(View.VISIBLE);
            chronometer.setBase(SystemClock.elapsedRealtime() - startTimeMillis);
            chronometer.start();
        }
        if ((chronometer != null) && (chronometer.getOnChronometerTickListener() == null))
            chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
                public void onChronometerTick(Chronometer paramAnonymousChronometer) {
                    if (timeLength.equals(paramAnonymousChronometer.getText()))
                        registerMessage(STOP_TIME, paramAnonymousChronometer);
                }
            });
    }

    private void stopTime(Chronometer chronometer) {
        if (chronometer != null) {
            chronometer.setVisibility(View.GONE);
            chronometer.stop();
            chronometer.setBase(SystemClock.elapsedRealtime());
        }
    }

    public void registerMessage(int paramInt, Object paramObject) {
        Message localMessage = this.handler.obtainMessage();
        localMessage.arg1 = paramInt;
        localMessage.what = paramInt;
        localMessage.obj = paramObject;
        this.handler.sendMessage(localMessage);
    }


}
